package stack

import (
	C "gitee.com/ljfirst/algo-go-sdk/common/constant"
)

/**
 * @author ljfirst
 * @version V1.0
 * @date 2023/6/28 19:06
 * @author-Email ljfirst@mail.ustc.edu.cn
 * @blogURL https://blog.csdn.net/ljfirst
 * @description
 * */
type MinStackOpt struct {
	ArrayStack
	minValue interface{}
}

func (m *MinStackOpt) GetMin() interface{} {
	if m.ArrayStack.Empty() {
		return C.ErrorNum
	}
	return m.minValue
}

func (m *MinStackOpt) Push(value interface{}) {
	gap := 0
	if m.ArrayStack.Empty() {
		m.minValue = value
	} else {
		gap = value.(int) - m.minValue.(int)
		if gap < 0 {
			m.minValue = value
		}
	}
	m.ArrayStack.Push(gap)
}

func (m *MinStackOpt) Pop() interface{} {
	if m.ArrayStack.Empty() {
		return C.ErrorNum
	}
	value := 0
	gap := m.ArrayStack.Pop().(int)
	if gap < 0 {
		value = m.minValue.(int)
		m.minValue = m.minValue.(int) - gap
	} else {
		value = m.minValue.(int) + gap
	}
	return value
}

func (m *MinStackOpt) Peak() interface{} {
	if m.ArrayStack.Empty() {
		return C.ErrorNum
	}
	value := 0
	gap := m.ArrayStack.Peak().(int)
	if gap < 0 {
		value = m.minValue.(int)
	} else {
		value = m.minValue.(int) + gap
	}
	return value
}

func (m *MinStackOpt) GetAttribute() *C.Attribute {
	return &C.Attribute{
		Tags: []string{C.MinStack},
		Desc: &C.Desc{
			Name:   "MinStackOpt",
			NameCn: "最小栈:优化",
			ParamsDesc: map[string]string{
				"ArrayStack": "内部维护一个数组来控制先进后出",
				"minValue":   "内部维护一个数值，存储当前栈的最小值",
			},
		},
	}
}
